package com.milepost.workflow.flowdefform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.milepost.workflow.flowdefform.entity.FlowDefFormEntity;
import com.milepost.workflow.flowdefform.mapper.FlowDefFormMapper;
import com.milepost.workflow.flowdefform.service.FlowDefFormService;
import com.milepost.workflow.util.UUIDUtil;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author huarf
 * @Description
 * @create 2022-03-26 16:38
 */
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class FlowDefFormServiceImpl extends ServiceImpl<FlowDefFormMapper, FlowDefFormEntity> implements FlowDefFormService {

    @Override
    public boolean createFlowDefForm(FlowDefFormEntity flowDefFormEntity) {

        int effectRow = 0;
        synchronized (this) {
            if (getByFlowDefId(flowDefFormEntity.getFlowDefId()) == null) {
                flowDefFormEntity.setId(UUIDUtil.randomUUID());
                effectRow = baseMapper.insert(flowDefFormEntity);
            } else {
                //根据条件更新，sql中只包含非空的字段
                //effectRow = baseMapper.update(flowDefFormEntity, new QueryWrapper<FlowDefFormEntity>().lambda().eq(FlowDefFormEntity::getFlowDefId, flowDefFormEntity.getFlowDefId()));

                //第一个参数传实体类，实体类中为空的字段不会出现在sql中，
                //第二个参数可以传更新条件和更新字段，可以实现将某个字段从非空更新成空。
                effectRow = baseMapper.update(flowDefFormEntity, Wrappers.<FlowDefFormEntity>lambdaUpdate()
                        .set(FlowDefFormEntity::getStructure, flowDefFormEntity.getStructure())//要更新的字段
                        .eq(FlowDefFormEntity::getFlowDefId, flowDefFormEntity.getFlowDefId()));//条件
            }
        }

        return effectRow > 0;
    }

    @Override
    public FlowDefFormEntity getByFlowDefId(String flowDefId) {

        FlowDefFormEntity flowDefFormEntity = baseMapper.selectOne(new QueryWrapper<FlowDefFormEntity>().lambda().eq(FlowDefFormEntity::getFlowDefId, flowDefId));

        return flowDefFormEntity;
    }

}
